// 引入算价组件
document.write("<script type='text/javascript' src='/statics/js/modules/component/calculatePriceComponent.js'></script>");
$(function () {
    vm.query();
});
var DUmsocx1;
var ws;
var flag=0;
function ToggleConnectionClicked() {
    try {
        /*
        //检测当前浏览器是否支持websocket模式
        window.WebSocket = window.WebSocket || window.MozWebSocket;
                  if (!window.WebSocket){
                              alert("WebSocket not supported by this browser");
                              return;
                  }*/
        ws = new WebSocket("ws://127.0.0.1:1818");//连接服务器

        ws.onopen = function(event){
            //alert("已经与服务器建立了连接\r\n当前连接状态："+this.readyState);
            flag=0;
            ws.send(DUmsocx1);
            //SendData(DUmsocx1);
        };
        ws.onmessage = function(event){
          /*  //截取数字
            if (event.data.substring(0,2) === '00'){ // 交易成功*/
                //请求后台业务
                vm.sweepCodeCallBack(event.data);
            /*}else{
                vm.loading.close();
                alert("接收到服务器发送的数据：\r\n"+event.data);
            }*/
            flag=1;
        };
        ws.onclose = function(event){
            //alert("已经与服务器断开连接\r\n当前连接状态："+this.readyState);
        };
        ws.onerror = function(event){
            if (flag!=1)
            // 关闭加载框
                alert("WebSocket接收异常！");
                vm.loading.close();
        };
    } catch (ex) {
        alert(ex.message);
    }
};
var vm = new Vue({
	el:'#rrapp',
	data: {
        showList: true,
        loading: null,
        userLoading:false,//客户加载
        showDetail: true,
        showEdit:false,
        title: null,
        memberList:[],//会员列表
        //表单对齐方式
        labelPosition: 'right',
        erpOrder: {memberName:'',shipName:'',orderCreatetime:'',tel:'',productionStatus:'',shipStatus:'',productionRequest:''},
        //用于接收生成批量结算单的对象
        batchProduct:{recMoney:[],totalMoney:0,erpOrder: {memberName:'',shipName:'',shipName:'',shipTel:'',shipArea:'',shipAddr:''},orderNos:'',curentUser:'',},
        //门店批量收款
        batchRecMoney:{},
        batchRecMoneyVisible:false,
        //发票信息
        orderTax:[],
        //添加订单校验规则
        addRules:{
            memberName:{ required: true, //是否必填
                message: '请选择客户', //规则
                trigger: 'blur'  //何事件触发
            },
            shipName:[
                { required: true,message:'请输入联系人',trigger: 'blur'}
                ],
            orderCreatetime:[
                { required: true,message:'请选择接单时间',trigger: 'blur'}
            ],
            projectName:[
                { type: 'string', max:100, message: '项目名称不能长于100字', trigger: 'blur' },
            ]
           /* tel:[{ pattern: /^1[34578]\d{9}$/, message:'请输入正确的手机号', trigger: 'blur'},
                ]*/
        },
        /* 打印快递单 */
        print: {
            orderInfo: {},
            orderItemList: []
        },
        e:{
            taxTypeEnum:[], //发票类型
            payTypeEnum:[],
        },
        q: {
            orderNo: '',
            memberName: '',
            projectName:'',
            isCancel:false,
            shipName: '',
            shipTel:'',
            orderSource: '',
            productionStatus: '',
            startTime: '',
            endTime: '',
            payStatus:'',
            //客户名称查询
            name: '',
            //产品搜索
            productName: '',
            //商务印刷中的二级选项卡id
            printZiyunCategoryId: null,
            //快印印刷中的二级选项卡id
            fastZiyunCategoryId: null,
            //工厂名称
            factoryName:'',
            //工厂地址
            factoryAddr:'',
        },
        //定义一个变量用于接收修改前的订单详情
        recordItemData:[],
		itemFile:{
			/* 保证 $.files_up_oss 在当前页面只初始化一次 */
			filesUpOss: false,
			/* 订单商品集合下标标识，获得当前正在操作的商品元素 */
			itemIndex: 0,
			/* 上传文件类型  source：源文件  send：发货图片 */
			itemFileType: 'source',
			/* 源文件上传图片列表 */
			itemSourceFiles: [],
			/* 发货上传图片列表 */
			itemSendFiles: [],
		},
        // 弹窗下载
		itemSourceFileTableVisible:false,
        //门店业务员列表
        salesManList: [],
        /* 省市区data */
        area: [],
        //订单状态:
        productionStatusEnum: [{value:'',label:'订单状态'},{value: '7', label: '新开单'}, {value: '3', label: '生产中'}, {
            value: '4', label: '生产完成'}, {value: '6', label: '已完成'}],
        //订单类型
        orderSourceEnum: [],
        //商品明细列表
        orderItemDetailData: [],
        //订单日志
        erpOrderLogData:[],
        //单个商品的详情
        singleOrderItemDetail: {},
        //订单备注对象
        orderRemarks:{orderNo:'',orRemarks:''},
        //取消订单（添加一条记录到erp_order_log）
        erpOrderLogs:{orderNo:'',logText:''},
        options: [],
        erpOrderProductionList:[],
        //客户选择弹出框
        userDialogVisible: false,
        //添加产品弹出框
        productDialogVisible: false,
        //阶梯价格弹出框
        stepPirceDialogVisible: false,
        //单个商品详情弹出框
        orderItemDetailDialogVisible: false,
        //标品分配
        itemAllotPageVisible: false,
        //印刷分配
        quoteItemAllotPageVisible:false,
        //订单修改
        updateOrderVisible: false,
        //订单备注
        remarksVisible:false,
        //取消订单
        cancelOrderVisible:false,
        //支付方式修改
        paymentChangeVisible:false,
        //制作要求
        productRequestDialogVisible:false,
        //订单出库
        HangingOrderOutVisible:false,
        //收银结算
        receviceMoneyVisible:false,
        //允许修改商品价格Flag
        updateItemPriceFlag:false,
        //允许修改订单优惠Flag
        updateOrderPmtGoodsFlag:false,
        /* 外协商添加 */
        suppFormVisible: false,
        /*下单按钮，防止重复下单*/
        orderVisible:true,
        suppForm: {
            orderId: '',
            eoItemId: '',
            originalItemId: '',
            cost:'',
        },
        suppOptions: [],
        /* 外协商选择页面 */
        supplierPageVisible: false,
        /* 外协商分页参数 */
        supplierPage:{
            currPage:1, // 当前页
            pageSize:8, // 分页数
            totalCount:0, // 总条数
            tableData:[], //数据列
        },
        /* 外协商分页查询参数 */
        supplierQuery: {
            supplierName: '',
            contactName: ''
        },
        //一键分配产品名称
        itemName:'',
        //添加订单是否显示可挂账
        credit:false,
        //日志弹出框
        erpOrderLogVisible:false,
        //收银对象
        recMoney:{
            discountRate: null, orderNo: '', memberName: '', totalMount: 0, memberId: 0, money: '',
            discount: null, payed: 0, advance: 0, payName: '', memo: '', serialCode: '', paymentId: ''
        },
        //客户列表
        userInfoData: [],
        //接单员列表:
        acceptOrderUserData: [],
        //阶梯价格数据:
        stepPriceData: [],
        //添加商品下方table数据
        goodsTableData: [],
        //订单详情table数据:
        detailData: [],
        //订单备注数据:
        orderRemarksData:[],
        //单个商品详情:
        singleItemData:[],
        formLabelWidth: '120px',
        sendType: [{value: '0', label: '快递'}, {value: '1', label: '自提'},{value: '2', label:'送货' }],
        //支付方式
        payTypeData: ["支付宝", "微信", "现金","银联","银联转账","预存款支付"],
        payTypeList:["支付宝", "微信", "现金","银联","银联转账"],
        payStatusEnum:[{value:'',label:'付款状态'},{value: "'0'", label: '未支付'}, {value: '1', label: '已支付'}, {value: '3', label: '部分支付'}],
        currentUser: '',
        goodsData: [],
        defaultProps: {children: 'children', label: 'label'},
        //用于提交订单
        erpOrderItemDto: {},
        //商务印刷二级选项卡数据(store_goods_category里面的二级分类)
        shangWuCategoryData: [],
        //快印二级选项卡数据
        fastCategoryData: [],
        //报价部件集合
        quotePartsList: [],
        //类型
        categoryType: null,
        //存放当前支付方式
        erpOrderPayNow:'',
        quoteProductInfo: {
        },
        courrentUser:'', //当前用户
        sellerInfoEntity:{}, //商户信息

        //分配工厂列表数据
        factoryInfosData:[],
        factoryQuoteInfos: [],// 原报价工厂列表
        factoryQuoteInfosQuery: [],// 过滤后报价工厂列表
        factoryStandardInfos: [],
        factoryStandardInfosQuery: [],
        //存放分配所需要的数据
        alloteData:{},
        //商务印刷相关信息
        quotePartShow:{},           // 部件是否展示
        quotePartsList:[],
        caculateQuoteData:{
            categoryType:'',         //分类
            attributesMap:{},       // 工艺属性
            selfPaperParts:{},      // 自来纸
            definitionValueMap:{},  // 自定义
        },
        material:{},                // 材料
        defineWheter:{},            // 开启定义信息
        defineArray:{},             // 自定义值数组
        craftWheter:{},             // 非必选工艺
        addCraft:{},                // 是否添加工艺
        quotePriceData:[],          //接收商务印刷返回的报价
        quotePriceVisible:false,    //是否展示算价相关信息
        //商务报价价格框
        factoryQuoteInfoList:[],
        //快印报价价格框
        fastFactoryQuoteInfoList:[],
        //商务销售价格弹出框
        quotePriceDialogVisible:false,
        //快印销售价格弹出框
        fastQuotePriceDialogVisible:false,
        //存储选中的商务印刷产品商务
        printGoods:{},
        //存储选中的快印印刷产品
        fastGoods:{},
        //存储选中的商务印刷索引
        printIndex:2,
        //存储选中的快印印刷索引
        fastIndex:0,
        //存放商务印刷销售金额
        printMoney:0,
        //存放快印销售金额：
        fastMoney:0,
        //订单详情中订单是否已分配
        isAllot:0,
        quoteFastPriceVisible:false,
        categoryData: {fast: {}, print: {}},
        count:0
    },
   /* watch:{
        'erpOrder.projectName':function (val) {
            this.erpOrder.projectName = vm.filterProjectName(val);
        }
    },*/
	methods: {
        query: function () {
            $.jgrid.gridUnload("#jqGrid");
            $("#jqGrid").jqGrid({
                url: baseURL + 'order/erporder/list',
                datatype: "json",
                colModel: [
                    {
                        label: '操作', name: 'operation', width: 50, align: 'center', title: false,
                        formatter: function (value, options, row) {
                            // 订单已作废
                            if (row.productionStatus === 11) {
                                return '--';
                            }
                            var html = '<li class="dropdown" style="list-style: none;position: absolute;width: 60px;right: auto;left: auto;"><a href="#" style="margin:0 auto;text-decoration:none;" class="dropdown-toggle" data-toggle="dropdown">操作</a>';
                            html += '<ul class="dropdown-menu"  style="min-width:100%;font-size: 12px;">';
                            var operations = [];
                            if (row.productionStatus === 3 || row.productionStatus === 7) {
                                if (row.orderSource == 2) {
                                    operations.push('<li><a href="javascript:;" onclick="return vm.orderEdit(\'' + options.rowId + '\');">订单修改</a></li><li class="divider"></li>');
                                }
                            }
                            if (row.productionStatus === 4) {
                                operations.push('<li><a href="javascript:;" onclick="return vm.openHangingOrderOut(\'' + options.rowId + '\');">订单出库</a></li><li class="divider"></li>');
                            }
                            if (row.productionStatus === 4 || row.productionStatus === 3) {
                                operations.push('<li><a href="javascript:;" onclick="return vm.orderRecall(\'' + options.rowId + '\');">订单撤回</a></li><li class="divider"></li>');
                            }
                            operations.push('<li><a href="javascript:;" onclick="return vm.orderRemark(\'' + options.rowId + '\');">订单备注</a></li><li class="divider"></li>');
                            operations.push('<li><a href="javascript:;" onclick="return vm.orderUrgent(\'' + options.rowId + '\');">订单加急</a></li><li class="divider"></li>');
                            if (row.orderSource == 1) {
                                operations.push('<li><a href="javascript:;" onclick="return vm.ziyunOrderBack(\'' + options.rowId + '\');">紫云网订单撤回</a></li><li class="divider"></li>');
                            }
                            operations.push('<li><a href="javascript:;" onclick="return vm.finishOrderItem(\'' + options.rowId + '\');">生产完成</a></li><li class="divider"></li>');
                            if (row.orderSource == 2) {
                                operations.push('<li><a href="javascript:;" onclick="return vm.openCancelDialog(\'' + options.rowId + '\');">取消订单</a></li><li class="divider"></li>');
                            }
                            if (row.commissionStatus === 0 && row.productionStatus === 6) {
                                operations.push('<li><a href="javascript:;" onclick="return vm.confirmCost(\'' + options.rowId + '\');">成本录入完成</a><li class="divider"></li>');
                            }
                            operations.push('<li><a href="javascript:;" onclick="return vm.openOrderLogi(\'' + options.rowId + '\');">添加物流</a></li>');
                            html += operations.join("")
                            html += '</ul></li>';
                            return html;
                        }
                    },
                    {
                        label: '订单号', name: 'orderNo', index: 'order_no', width: 90,
                        formatter: function (value, options, row) {
                            return '<a href="javascript:;" onclick="return vm.erpOrderDetail(\'' + row.orderNo + '\');">' + row.orderNo + '</a></li>';
                        }
                    },
                    {label: '订单号', name: 'orderNo', index: 'order_no', width: 90, key: true, hidden: true},
                    {label: '客户名称', name: 'memberName', index: 'member_name', width: 100, align: 'center'},
                    {label: '联系人', name: 'shipName', index: 'ship_name', width: 60, align: 'center'},
                    {label: '联系方式', name: 'shipMobile', index: 'ship_mobile', width: 80},
                    {
                        label: '打印', width: 100, align: 'center',
                        formatter: function (value, options, row) {
                            var actions = []
                            if (row.source != 'erp') {
                                actions.push('<a href="javascript:void(0);" onclick="return vm.printProdution(\'' + row.orderNo + '\',\'' + row.productionStatus + '\');">生产单</a>&nbsp;&nbsp;|');
                                actions.push('<a href="javascript:;" onclick="return vm.printBalancePage(\'' + row.orderNo + '\');">结算单</a>&nbsp;&nbsp;|');
                                actions.push('<a href="javascript:void(0);" onclick="return vm.printSendGoods(\'' + row.orderNo + '\');">购</a>');
                            } else {
                                actions.push('<a href="javascript:void(0);" onclick="return vm.printProdution(\'' + row.orderNo + '\',\'' + row.productionStatus + '\');">生产单</a>&nbsp;&nbsp;|');
                                actions.push('<a href="javascript:;" onclick="return vm.printBalancePage(\'' + row.orderNo + '\');">结算单</a>');
                            }
                            return actions.join('  ');
                        }
                    },
                    {
                        label: '文件', width: 60, align: 'center',
                        formatter: function (value, options, row) {
                            var actions = [];
                            if (row.source != 'erp') {
                                actions.push('<a href="filemanage:' + row.orderNo + '">文件</a>&nbsp;&nbsp;|');
                                actions.push('<a href="javascript:void(0);" onclick=" vm.showFileTable(' + options.rowId + ');">下载</a>');
                            } else {
                                actions.push('<a href="filemanage:' + row.orderNo + '">文件</a>&nbsp;&nbsp;');
                            }
                            return actions.join('  ');
                        }
                    },
                    {
                        label: '生产状态', name: 'productionStatus', index: 'production_status', width: 50, align: 'center',
                        formatter: function (value) {
                            switch (value) {
                                case 1:
                                    return '待审核';
                                case 2:
                                    return '待分配';
                                case 3:
                                    return '生产中';
                                case 4:
                                    return '<span style="color: #ae81ff">生产完成</span>';
                                case 5:
                                    return '已发货';
                                case 6:
                                    return '<span style="color: red">已完成</span>';
                                case 7:
                                    return '新开单';
                                case 11:
                                    return '已作废';
                                default:
                                    return "未知状态";
                            }
                        }
                    },
                    {
                        label: '发货状态', name: 'shipStatus', index: 'ship_status', width: 50, align: 'center',
                        formatter: function (value) {
                            switch (value) {
                                case 0:
                                    return '未发货';
                                case 1:
                                    return '已发货';
                                case 2:
                                    return '部分发货';
                            }
                        }
                    },
                    {
                        label: '收货状态', name: 'receivedStatus', index: 'received_status', width: 50, align: 'center',
                        formatter: function (value) {
                            return value == 0 ? '未收货' : '已收货'
                        }
                    },
                    {
                        label: '付款状态', name: 'payStatus', index: 'pay_status', width: 50, align: 'center',
                        formatter: function (value) {
                            switch (value) {
                                case 0:
                                    return '未支付';
                                case 1:
                                    return '已支付';
                                case 3:
                                    return '部分支付';
                                case 6:
                                    return '待审核';
                            }
                        }
                    },
                    {label: '支付方式', name: 'payment', index: 'payment', width: 50, align: 'center'},
                    {label: '商品总额', name: 'totalAmount', index: 'total_amount', width: 50, align: 'center'},
                    {
                        label: '优惠金额', name: '', index: '', width: 50, align: 'center',
                        formatter: function (value, options, row) {
                            var pmtGoods = row.pmtGoods;
                            var pmtOrder = row.pmtOrder;
                            var pmtRandom = row.pmtRandom;
                            var total = Number(pmtGoods) + Number(pmtOrder) + Number(pmtRandom);
                            total = Math.floor(total * 1000) / 1000;
                            total = total.toFixed(3);
                            return total;
                        }
                    },
                    {label: '调价', name: 'discount', index: 'discount', width: 50, align: 'center'},
                    {label: '应付金额', name: 'payableAmount', index: 'payable_amount', width: 50, align: 'center'},
                    {label: '已支付金额', name: 'payed', index: 'payed', width: 50, align: 'center'},
                    {label: '加急', name: 'isUrgent', index: 'is_urgent', width: 80, hidden: true},
                    {label: '业务员', name: 'merchantsSalesMan', index: 'merchants_sales_man', width: 50, align: 'center'},
                    {label: '下单时间', name: 'orderCreatetime', index: 'order_createtime', width: 80},
                    {
                        label: '项目名称', name: 'projectName', index: 'project_name', width: 80, align: 'center',
                        formatter: function (value) {
                            if (value) {
                                return "<b style='color: red'>" + value + "</b>";
                            } else {
                                return "";
                            }
                        }
                    },
                    {
                        label: '成本录入状态',
                        name: 'commissionStatus',
                        index: 'commission_status',
                        width: 60,
                        align: 'center',
                        formatter: function (value) {
                            switch (value) {
                                case 0:
                                    return '未录入';
                                case 1:
                                    return '已录入';
                                case 2:
                                    return '已计算';
                            }
                        }
                    },
                    {
                        label: '日志', width: 50, align: 'center',
                        formatter: function (value, options, row) {
                            var actions = [];
                            actions.push('<a href="javascript:void(0);" onclick="return vm.erpOrderLogDetail(\'' + row.orderNo + '\');">日志</a>');
                            return actions.join('  ');
                        }
                    },
                ],
                viewrecords: true,
                height: window.innerHeight - 120,
                rowNum: 25,
                rowList: [25, 50, 75],
                rownumbers: true,
                rownumWidth: 25,
                autowidth: true,
                multiselect: true,
                /* shrinkToFit:false,
                 autoScroll: true,*/
                pager: "#jqGridPager",
                jsonReader: {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount",
                    userdata: "userData"
                },
                postData: {
                    'orderNo': vm.q.orderNo,
                    'memberName': vm.q.memberName,
                    'shipName': vm.q.shipName,
                    'shipTel': vm.q.shipTel,
                    'orderSource': vm.q.orderSource,
                    'productionStatus': vm.q.productionStatus,
                    'startTime': vm.q.startTime,
                    'endTime': vm.q.endTime,
                    'projectName': vm.q.projectName,
                    'isCancel': vm.q.isCancel,
                    'payStatus':vm.q.payStatus
                },
                prmNames: {
                    page: "page",
                    rows: "limit",
                    order: "order",
                },
                gridComplete: function () {
                    //隐藏grid底部滚动条
                    $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "scroll"});
                    var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
                    vm.categoryData = userData.categoryData;
                    vm.orderSourceEnum = userData.orderSourceEnum;
                    vm.salesManList = userData.salesManList;
                    vm.area = JSON.parse(userData.area);
                    //循环判断是否为加急，加急添加背景色
                    var ids = $("#jqGrid").getDataIDs();
                    for (var i = 0; i < ids.length; i++) {
                        var rowData = $("#jqGrid").getRowData(ids[i]);
                        if (rowData.isUrgent == 1) {//如果加急状态等于1，则背景色置绿显示
                            $('#' + ids[i]).find("td").css("background-color", "pink");
                        }
                    }
                },
            });
        },
        add: function () {
            this.$refs['addForm'].clearValidate();
            vm.showList = false;
            vm.title = "添加订单";
            vm.detailData = [];
            var date = vm.orderCreatetimeFormat();
            vm.erpOrder = {
                acceptOrderUser: null, production_request: null, memo: null, productionStatus: null,
                memberName: null, orderSource: null, payStatus: null, shipStatus: null, receivedStatus: null,
                deposit: false, merchantsSalesMan: null, sendType: '1',
                orderCreatetime: date
            };
            //查询接单员列表(pop_sys_user表)以及所有快印以及商务印刷的数据
            var url = "order/erporder/addData"
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                success: function (r) {
                    if (r.code === 0) {
                        vm.acceptOrderUserData = r.acceptOrderUserData;
                        vm.erpOrder.acceptOrderUser = r.currentUser;
                        vm.categoryData.print = r.shangWuCategoryData
                        vm.categoryData.fast = r.fastCategoryData;
                        vm.erpOrder.merchantsSalesMan = vm.salesManList[0];
                    } else {
                        alert(r.msg);
                    }
                }
            });

        },
        /* 订单调价 */
        sumDiscount: function () {

        },
        update: function (event) {
            var orderNo = getSelectedRow();
            if (orderNo == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(orderNo)
        },
        saveOrUpdate: function (event) {
            var self=this;
            vm.$refs["addForm"].validate((valid) => {
                if (valid) {
                    var url = "order/erporder/save";
                    //先拼接参数
                    vm.erpOrderItemDto.erpOrder = vm.erpOrder;
                    vm.erpOrderItemDto.storeGoodsProductList = vm.detailData;
                    /*if (vm.erpOrderItemDto.storeGoodsProductList.length == 0) {
                        alert("请至少选择一种产品！")
                        return;
                    }*/
                    //先将按钮置为隐藏
                    vm.orderVisible = false;
                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(vm.erpOrderItemDto),
                        success: function (r) {
                            if (r.code === 0) {
                                alert('操作成功', function (index) {
                                    self.$refs.calculatePrice.getMemberId(99999999);
                                    vm.orderVisible = true;
                                    vm.reload();
                                });
                            } else {
                                alert(r.msg);
                                vm.orderVisible = true;
                            }
                        }
                    });
                } else {
                    this.$message({
                        message: '请填写完信息再进行下单',
                        type: 'warning'
                    });
                }
            })
        },
        del: function (event) {
            var orderNos = getSelectedRows();
            if (orderNos == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "erpOrder/erporder/delete",
                    contentType: "application/json",
                    data: JSON.stringify(orderNos),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (orderNo) {
            $.get(baseURL + "order/erporder/info/" + orderNo, function (r) {
                if(r.code==0){
                    vm.erpOrder = r.erpOrder;
                    if(vm.erpOrder.shipMobile){
                        vm.erpOrder.shipMobile=vm.erpOrder.shipMobile;
                    }
                    if(vm.erpOrder.shipTel){
                        vm.erpOrder.shipMobile=vm.erpOrder.shipTel;
                    }
                    vm.orderRemarksData = r.orderRemarksData;
                    vm.erpOrderProductionList = r.erpOrderProductionList;
                    vm.orderTax = r.orderTax;
                    vm.isAllot = r.isAllot;
                    vm.e.taxTypeEnum = r.taxTypeEnum;
                    //格式化数据vm.e
                    var productionStatus = vm.erpOrder.productionStatus;
                    switch (productionStatus) {
                        case 1:
                            vm.erpOrder.productionStatus = '待审核';
                            break;
                        case 2:
                            vm.erpOrder.productionStatus = '待分配';
                            break;
                        case 3:
                            vm.erpOrder.productionStatus = '生产中';
                            break;
                        case 4:
                            vm.erpOrder.productionStatus = '生产完成';
                            break;
                        case 5:
                            vm.erpOrder.productionStatus = '已发货';
                            break;
                        case 6:
                            vm.erpOrder.productionStatus = '已完成';
                            break;
                        case 7:
                            vm.erpOrder.productionStatus = '新开单';
                            break;
                    }
                    var shipStatus = vm.erpOrder.shipStatus;
                    switch (shipStatus) {
                        case 0:
                            vm.erpOrder.shipStatus = '未发货';
                            break;
                        case 1:
                            vm.erpOrder.shipStatus = '已发货';
                            break;
                        case 2:
                            vm.erpOrder.shipStatus = '部分发货';
                            break;
                    }
                    var payStatus = vm.erpOrder.payStatus;
                    switch (payStatus) {
                        case 0:
                            vm.erpOrder.payStatus = '未支付';
                            break;
                        case 1:
                            vm.erpOrder.payStatus = '已支付';
                            break;
                        case 3:
                            vm.erpOrder.payStatus = '部分支付';
                            break;
                    }
                    vm.recordItemData = JSON.parse(JSON.stringify(r.orderItemDetailData));
                    vm.orderItemDetailData = r.orderItemDetailData;
                    //处理数据
                    if (vm.orderItemDetailData.length > 0) {
                        for (var i = 0; i < vm.orderItemDetailData.length; i++) {
                            var item = vm.orderItemDetailData[i];
                            // cutModel 转换
                            if (!$.isEmptyObject(item.cutModel)) {
                                item.cutModelObj = JSON.parse(item.cutModel);
                            }
                            //处理工艺
                        }
                    }
                }else{
                    alert(r.msg);
                }

            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.showDetail = true;
            vm.orderVisible = true;
            this.$refs.calculatePrice.memberId = null;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page,
                postData: {
                    'orderNo': vm.q.orderNo,
                    'memberName': vm.q.memberName,
                    'shipName': vm.q.shipName,
                    'shipTel': vm.q.shipTel,
                    'orderSource': vm.q.orderSource,
                    'productionStatus': vm.q.productionStatus,
                    'startTime': vm.q.startTime,
                    'endTime': vm.q.endTime,
                    'projectName': vm.q.projectName,
                    'isCancel': vm.q.isCancel,
                    'payStatus':vm.q.payStatus
                },
            }).trigger("reloadGrid");
        },

        //文件下载列表
        showFileTable: function (orderNo) {
            $.ajax({
                type: "GET",
                url: baseURL + "order/useraccessory/userAccessorysByOrder/" + orderNo,
                contentType: "application/json",
                data: [],
                success: function (r) {
                    if (r.code == 0) {
                        vm.itemSourceFileTableVisible = true;
                        vm.itemFile.itemIndex = orderNo;
                        vm.itemFile.itemSourceFiles = r.list;
                    } else {
                        alert(r.msg);
                    }

                }

            });
        },
        /* 商品原文件下载 */
        itemSourceFileDownload: function (data) {
            window.location.href = baseURL + "order/useraccessory/download/" + data.id;
        },


        /* 外协商添加表单 */
        suppFormShow: function (row) {
            vm.suppForm.orderId = row.orderNo;
            vm.suppForm.eoItemId = row.eoItemId;
            vm.suppForm.originalItemId = row.originalItemId;
            vm.querySupplierPageList();
            vm.supplierPageVisible = true;
        },

        /* 查询外协商列表 */
        querySupplierPageList: function () {
            var queryData = {
                "limit": vm.supplierPage.pageSize,
                "page": vm.supplierPage.currPage,
                "supplierName": vm.supplierQuery.supplierName
            }
            $.ajax({
                type: "GET",
                url: baseURL + "suppOffline/erpsupplieroffline/list",
                contentType: "application/json",
                data: queryData,
                success: function (r) {
                    vm.supplierPage.tableData = r.page.list
                    vm.supplierPage.totalCount = r.page.totalCount
                }
            });
        },

        /*分页数改变*/
        handleSizeChange: function (val) {
            vm.supplierPage.pageSize = val;
            vm.querySupplierPageList();
        },
        /*分页当前页改变改变*/
        handleCurrentChange: function (val) {
            vm.supplierPage.currPage = val
            vm.querySupplierPageList();
        },
        /* 选择外协商 */
        suppFormCheck: function (row) {
            vm.suppForm.supplierId = row.supplierId;
            vm.suppForm.attributeName = '';
            vm.suppForm.cost = 0;
            vm.suppForm.csRemark = '';
            vm.suppFormVisible = true;
        },
        /* 保存外协商信息 */
        suppFormSave: function () {
            var postData = {
                orderId: vm.suppForm.orderId,
                eoItemId: vm.suppForm.eoItemId,
                supplierId: vm.suppForm.supplierId,
                cost: vm.suppForm.cost,
                attributeName: vm.suppForm.attributeName,
                originalItemId: vm.suppForm.originalItemId,
                csRemark: vm.suppForm.csRemark
            };
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/suppSave",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function (r) {
                    if (r.code == 0) {
                        vm.suppFormVisible = false;
                        vm.supplierPageVisible = false;
                        vm.getInfo(vm.suppForm.orderId);
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },

        //报价商品修改份数
        changCopy:function(row){
            row.total=(row.copy*row.price).toFixed(2);
        },

        itemSourceFileDelete: function (data) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm') {
                        var ids = [data.id];
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/useraccessory/delete",
                            contentType: "application/json",
                            data: JSON.stringify(ids),
                            success: function (r) {
                                if (r.code === 0) {
                                    // vm.getInfo(vm.erpOrder.orderNo);
                                    vm.showFileTable(vm.itemFile.itemIndex);
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },


        //格式化date_time-picker数据
        orderCreatetimeFormat() {
            let date = new Date();
            let Y = date.getFullYear();
            let M = date.getMonth() + 1
            M = (M < 10 ? '0' + M : M);
            let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
            let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
            let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
            let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
            return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
        },

        //重置查询条件:
        reset() {
                vm.q.orderNo = '',
                vm.q.memberName = '',
                vm.q.shipName = '',
                vm.q.shipTel = '',
                vm.q.orderSource = '',
                vm.q.productionStatus = '',
                vm.q.startTime = '',
                vm.q.endTime = '',
                vm.q.projectName = '',
                vm.q.isCancel = false
                vm.q.payStatus ='';
            vm.reload();
        },
        // 省市区
        handleItemChange: function (val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length - 1];
            var lableVal = vm.getCascaderObj(val, vm.area);
            vm.erpOrder.shipAreaId = areaId;
            var area = lableVal.join(',').replace(new RegExp(',', 'g'), ' ');
            vm.erpOrder.shipArea = area;
        },
        //选择客户
        openUserDialog: function () {
            vm.userDialogVisible = true;
            this.$nextTick(function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "order/erporder/queryPageUser",
                    contentType: "application/json",
                    postData: {
                        'name': vm.q.name
                    },
                    success: function (r) {
                        if (r.code == 0) {
                            vm.userInfoData = r.userInfoData;
                            vm.memberList=vm.userInfoData.map(item =>{
                                return { value: item.userId, label: item.name };
                            })
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            })
        },
        queryUser: function (query) {
            var self=this;
            if (query !== '') {
                self.userLoading = true;
                setTimeout(() => {
                    self.userLoading = false;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "order/erporder/queryUser",
                        data: {"name": query},
                        success: function (r) {
                            if (r.code == 0) {
                                vm.userInfoData = r.userInfoData;
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                }, 200);
            }
        },
        //双击选中客户，同时关闭弹出框
        selectUser: function (val) {
            var row={};
            //判断是否已经商品，如果有，提示先删除商品，再修改客户
            if (vm.detailData.length > 0) {
                alert("请删除商品后再修改客户!");
                return;
            }
            for(var i=0;i<vm.userInfoData.length;i++){
                if(vm.userInfoData[i].userId===val){
                    row=vm.userInfoData[i];
                }
            }
            vm.erpOrder.memberId = row.userId;
            vm.erpOrder.memberName = row.name;
            if (row.tel == '' || row.tel == null) {
                vm.erpOrder.shipTel = row.mobile;
            } else {
                vm.erpOrder.shipTel = row.tel;
            }
            if (row.merchantsSalesMan != '' && row.merchantsSalesMan != null) {
                vm.erpOrder.merchantsSalesMan = row.merchantsSalesMan;
            }
            vm.erpOrder.shipAddr = row.address;
            vm.erpOrder.shipName = row.nickname;
            vm.credit = row.hangsAccountCustomer;
            vm.erpOrder.onCredit = row.hangsAccountCustomer;
            //vm.userDialogVisible = false;
            this.$refs.calculatePrice.getMemberId(vm.erpOrder.memberId);
        },
        //选择接单员
        selectAcceptUser: function (val) {
            vm.erpOrder.acceptOrderUser = val;
        },
        //弹出添加框
        addProductDialog: function () {
            vm.productDialogVisible = true;
            vm.goodsTableData = [];
            vm.goodsData = [];
        },
        //分类被点击触发事件,查找当前分类下的材料
        handleNodeClick(data) {
            var categoryId = data.categoryId;
            var memberId = vm.erpOrder.memberId;
            if (isBlank(memberId)) {
                memberId = 99999999;//如果没选择客户，给个默认值
            }
            $.get(baseURL + "order/erporder/productInfo/" + categoryId + "/" + memberId, function (r) {
                vm.goodsData = r.goodsData;
            });
        },
        //产品搜索
        productSearch: function () {
            var memberId = vm.erpOrder.memberId;
            if (isBlank(memberId)) {
                memberId = 99999999;//如果没选择客户，给个默认值
            }
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/productSearch",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                data: {"productName": vm.q.productName, "memberId": memberId},
                success: function (r) {
                    if (r.code == 0) {
                        vm.goodsData = r.goodsData
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //添加商品到添加商品弹出框下方table中
        addProduct: function (row) {
            if (row.price == null && row.stepPrice == '[]') {
                alert("请先维护价格！");
                return;
            }
            if (row.goodsType == "standard" || row.goodsType == "design") {
                //深克隆
                var item = JSON.parse(JSON.stringify(row));
                item.copy = 1;
                item.quantity = 1;
                item.total = item.price * item.copy * item.quantity.toFixed(2);
                // item.goodsType='standard';
                vm.goodsTableData.push(item);
            }
            //如果为广告物料以及按周长计算或者按长度
            if (row.goodsType == "material" && (row.pricingManner == 1 || row.pricingManner == 2)) {
                //深克隆
                var item = JSON.parse(JSON.stringify(row));
                item.length = 1;
                item.quantity = 1;
                item.total = item.price;
                item.goodsType = 'material';
                vm.goodsTableData.push(item);
            }
            //如果为广告物料以及按面积计算
            if (row.goodsType == "material" && row.pricingManner == 0) {
                //深克隆
                var item = JSON.parse(JSON.stringify(row));
                item.width = 1;
                item.length = 1;
                item.quantity = 1;
                item.total = item.price;
                item.goodsType = 'material';
                vm.goodsTableData.push(item);
            }
        },
        //删除选中的商品
        deleteProduct: function (index, goodsTableData) {
            vm.goodsTableData.splice(index, 1);
        },
        //把添加的商品添加到订单详情table中
        addToMainTable: function () {
            if (vm.goodsTableData.length == 0) {
                alert("请至少添加一个商品!");
                return;
            }
            //重新封装数据
            var goodTableData = [];
            //判断是否为广告物料，
            for (let i = 0; i < vm.goodsTableData.length; i++) {
                var row = vm.goodsTableData[i];
                if (row.goodsType == "standard" || row.goodsType == 'design') {
                    goodTableData.push(row);
                } else if (row.goodsType == "material") {
                    var item = JSON.parse(JSON.stringify(row));
                    if (row.pricingManner == 1) {
                        item.craft = item.craft + ",周长:" + item.length;
                    } else if (row.pricingManner == 2) {
                        item.craft = item.craft + ",长度:" + item.length;
                    } else {
                        item.craft = item.craft + ",面积:" + item.length + "*" + item.width;
                    }
                    goodTableData.push(item);
                }
            }
            vm.detailData.push.apply(vm.detailData, goodTableData);
            vm.productDialogVisible = false;
        },
        //取消添加
        cancelAdd: function () {
            this.$confirm('此操作将取消添加产品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //将添加的商品数据清除:
                vm.goodsTableData = []
                vm.goodsData = []
                vm.productDialogVisible = false;
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        getCascaderObj(val, opt) {
            return val.map(function (value, index, array) {
                for (var itm in opt) {
                    if (opt[itm].value == value) {
                        var label = opt[itm].label;
                        opt = opt[itm].children;
                        return label;
                    }
                }
                return null;
            });
        },
        //商品明细列表查看单个商品详情
        itemDetail: function (row) {
            var eoItemId = row.eoItemId;
            vm.singleItemData = [];
            //查询
            var url = "order/erporder/singleOrderItemDetail/" + eoItemId
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                success: function (r) {
                    if (r.code === 0) {
                        vm.singleOrderItemDetail = r.singleOrderItemDetail;
                        vm.singleItemData.push(vm.singleOrderItemDetail);
                        vm.orderItemDetailDialogVisible = true;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //格式化分配情况展示
        formatterStatus: function (row, column, cellValue) {
            if (cellValue == '1') {
                return '待分配'
            } else if (cellValue == '2') {
                return '生产中'
            } else if (cellValue == '3') {
                return '已完成'
            } else if (cellValue == '4') {
                return '已发货'
            }
        },
        formatPricingManner: function (row, column, cellValue) {
            if (cellValue == 0) {
                return '按面积计价'
            } else if (cellValue == 1) {
                return '按周长计价'
            } else {
                return '按长度计价'
            }
        },

        //一键分配
        oneKeyAllot: function (row) {
            vm.alloteData.orderNo = row.orderNo;
            vm.alloteData.eoItemId = row.eoItemId;
            var eoItemId = row.eoItemId;
            //判断是标品分还是印刷快印分配
            if (row.addcartBuyType != "fast" && row.addcartBuyType != "print") {
                //标品分配url
                var url = baseURL + "order/erporder/orderItemAllotFindFactory/" + eoItemId;
                $.get(url, function (r) {
                    if (r.code == 0) {
                        vm.factoryStandardInfos = r.factoryInfosQuery;
                        vm.factoryStandardInfosQuery = r.factoryInfosQuery;
                        vm.itemName = row.name;
                        vm.itemAllotPageVisible = true;
                    } else {
                        alert(r.msg);
                    }
                })
            } else {
                //报价商品分配
                var url = baseURL + "order/erporder/quoteOrderItemAllotFindFactory/" + eoItemId;
                $.get(url, function (r) {
                    if (r.code == 0) {
                        vm.factoryQuoteInfos = r.factoryQuoteInfos;
                        vm.factoryQuoteInfosQuery = r.factoryQuoteInfos;
                        vm.itemName = row.name;
                        vm.quoteItemAllotPageVisible = true;
                    } else {
                        alert(r.msg);
                    }
                })
            }

        },
        //上传文件
        upload: function (orderNo) {
            alert(orderNo);
        },

        queryFactoryStandard: function () {
            var factoryName = vm.q.factoryName;
            if (isBlank(factoryName)) {
                vm.factoryStandardInfosQuery = vm.factoryStandardInfos;
            } else {
                vm.factoryStandardInfosQuery = [];
                for (var f in vm.factoryStandardInfos) {
                    var queryNameHit = false;
                    var item = vm.factoryStandardInfos[f];
                    if (!isBlank(factoryName)) {
                        if (item.sellerDetail.merchantName.indexOf(factoryName) != -1) {
                            queryNameHit = true;
                        }
                    } else {
                        queryNameHit = true;
                    }
                    if (queryNameHit) {
                        vm.factoryStandardInfosQuery.push(item);
                    }
                }
            }
        },
        //搜索工厂
        searchFactory: function () {
            var factoryName = vm.q.factoryName;
            var factoryAddr = vm.q.factoryAddr;
            if (isBlank(factoryName) && isBlank(factoryAddr)) {
                vm.factoryQuoteInfosQuery = vm.factoryQuoteInfos;
            } else {
                vm.factoryQuoteInfosQuery = [];
                for (var f in vm.factoryQuoteInfos) {
                    var queryNameHit = false;
                    var queryAddrHit = false;
                    var item = vm.factoryQuoteInfos[f];
                    if (!isBlank(factoryName)) {
                        if (!isBlank(item.factoryInfoVO.factoryName) && item.factoryInfoVO.factoryName.indexOf(factoryName) != -1) {
                            queryNameHit = true;
                        }
                    } else {
                        queryNameHit = true;
                    }
                    if (!isBlank(factoryAddr)) {
                        if (!isBlank(item.factoryInfoVO.address) && item.factoryInfoVO.address.indexOf(factoryAddr) != -1) {
                            queryAddrHit = true;
                        }
                    } else {
                        queryAddrHit = true;
                    }
                    if (queryNameHit && queryAddrHit) {
                        vm.factoryQuoteInfosQuery.push(item);
                    }
                }
            }

        },

        /* 标品分配 */
        itemAllotSave: function (row) {
            var factoryName = row.sellerDetail.merchantName;
            var producer = row.sellerDetail.merchantId;
            var cost = row.basePriceDetail.totalPrice;
            var self = row.sellerDetail.isSelf;
            this.$confirm('确认分配至 ' + factoryName + ' ?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm') {
                        var postData = {
                            orderNo: vm.alloteData.orderNo,
                            erpItemId: vm.alloteData.eoItemId,
                            producer: producer,
                            cost: cost,
                            self: self,
                        };
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/erporder/allotOrderItem",
                            contentType: "application/json",
                            data: JSON.stringify(postData),
                            success: function (r) {
                                if (r.code == 0) {
                                    vm.itemAllotPageVisible = false;
                                    //重新查询订单信息
                                    vm.getInfo(vm.alloteData.orderNo);
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 报价商品分配 */
        quoteItemAllotSave: function (row) {
            var factoryName = row.factoryInfoVO.factoryName;
            var id = row.factoryInfoVO.id;
            var totalPrice = row.totalPrice;
            var self = row.factoryInfoVO.self;
            this.$confirm('确认分配至 ' + factoryName + ' ?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm') {
                        var postData = {
                            orderNo: vm.alloteData.orderNo,
                            erpItemId: vm.alloteData.eoItemId,
                            producer: id,
                            cost: totalPrice,
                            self: self,
                            /*  csId: vm.erpOrder.csId,
                              pmcId: vm.erpOrder.pmcId*/
                        };
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/erporder/allotOrderItem",
                            contentType: "application/json",
                            data: JSON.stringify(postData),
                            success: function (r) {
                                if (r.code == 0) {
                                    vm.quoteItemAllotPageVisible = false;
                                    vm.getInfo(vm.alloteData.orderNo);
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },


        //工序分配
        craftAllot: function (row) {
            window.craftsAllotPageVm.loadData({
                sellerId: vm.erpOrder.thirdMerchantId,
                orderNo: vm.erpOrder.orderNo,
                totalAmount: vm.erpOrder.totalAmount,
                // itemId: row.originalItemId,
                erpItemId: row.eoItemId,
                itemName: row.name,
                productId: row.productId
            });
        },

        /* 分配选项删除 */
        delAllotItem: function (value) {
            this.$confirm('此操作将删除分配信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/erporder/deleteAllotItem?productionId=" + value,
                            contentType: "application/json",
                            success: function (r) {
                                if (r.code == 0) {
                                    vm.getInfo(vm.erpOrder.orderNo);
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        //查看订单详情
        erpOrderDetail: function (orderNo) {
            vm.erpOrder = {
                acceptOrderUser: null, productionRequest: null, memo: null, productionStatus: null,
                memberName: null, orderSource: null, payStatus: null, shipStatus: null, receivedStatus: null,
                deposit: false,
                orderCreatetime: null
            };
            vm.isAllot = 0;
            vm.getInfo(orderNo);
            vm.title = "订单详情";
            vm.showDetail = false;
        },


        //订单加急
        orderUrgent: function (id) {
            var rowData = $("#jqGrid").jqGrid('getRowData', id);
            this.$confirm(rowData.isUrgent == 0 ? '是否确认订单加急?' : '是否确认取消订单加急', rowData.isUrgent == 0 ? '订单加急提示' : '取消订单加急提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var orderNo = id;
                $.get(baseURL + "order/erporder/orderUrgent/" + orderNo, function (r) {
                    if (r.code == 0) {
                        alert("操作成功");
                        vm.reload();
                    } else {
                        alert(r.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },

        addProductRequest: function (id) {
            var rowData = $("#jqGrid").jqGrid('getRowData', id);
            //获取门店制作要求
            vm.erpOrder.orderNo = rowData.orderNo;
            vm.erpOrder.productionRequest = rowData.productionRequest;
            vm.productRequestDialogVisible = true;
        },
        //向后台发起请求添加制作要求
        addprodRequest() {
            $.get(baseURL + "order/erporder/addprodRequest/" + rowData.orderNo, function (r) {
                if (r.code == 0) {
                    alert("操作成功");
                    vm.reload();
                } else {
                    alert(r.msg);
                }
            })
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/addprodRequest",
                contentType: "application/json",
                data: JSON.stringify(vm.erpOrder.orderNo),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            vm.productRequestVisible = false;
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },

        //订单修改
        orderEdit: function (id) {
            var orderNo = id;
            window.erpOrderEditVm.loadData({
                'orderNo': orderNo,
                'title': '订单修改'
            });
        },

        //生产完成
        finishOrderItem: function (id) {
            //获取选中行的订单号
            // var id=$('#jqGrid').jqGrid('getGridParam','selrow');
            if (id == null) {
                alert("请选中一行");
                return;
            }
            this.$confirm('是否确认生产完成?', '生产完成提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var orderNo = id;
                $.get(baseURL + "order/erporder/finishOrderItem/" + orderNo, function (r) {
                    if (r.code == 0) {
                        alert("操作成功");
                        vm.reload();
                    } else {
                        alert(r.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        //紫云网订单撤回
        ziyunOrderBack: function (orderNo) {
            $.get(baseURL + "order/erporder/ziyunOrderBack/" + orderNo, function (r) {
                if (r.code == 0) {
                    alert("操作成功");
                    vm.reload();
                } else {
                    alert(r.msg);
                }
            })
        },

        //新增备注(打开dialog框)
        orderRemark: function (orderNo) {
            vm.orderRemarks.orOrderId = orderNo;
            vm.orderRemarks.orRemarks = '';
            vm.remarksVisible = true;
        },
        addRemark: function () {
            if (vm.orderRemarks.orRemarks == '') {
                alert("添加备注不能为空");
                return;
            }
            //发送请求添加备注
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/addRemark",
                contentType: "application/json",
                data: JSON.stringify(vm.orderRemarks),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            vm.remarksVisible = false;
                            $("#jqGrid").trigger("reloadGrid");
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //打开取消订单dialog
        openCancelDialog: function (id) {
            //获取选中行的订单号
            // var orderNo=$('#jqGrid').jqGrid('getGridParam','selrow');
            if (id == null) {
                alert("请选中一行");
                return;
            }
            vm.erpOrderLogs.orderNo = id;
            vm.erpOrderLogs.logText = '';
            vm.cancelOrderVisible = true
        },
        cancelOrder: function () {
            if (vm.erpOrderLogs.logText == '') {
                alert("取消原因不能为空");
                return;
            }
            //发送请求添加备注
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/cancelOrder",
                contentType: "application/json",
                data: JSON.stringify(vm.erpOrderLogs),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            vm.cancelOrderVisible = false;
                            $("#jqGrid").trigger("reloadGrid");
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //打开支付方式修改框
        openPayment: function () {
            var orderNo = getSelectedRow();
            if (orderNo == null) {
                return;
            }
            var rowData = $("#jqGrid").jqGrid('getRowData', orderNo);
            //获取当前支付方式
            vm.erpOrderPayNow = rowData.payment;
            vm.erpOrder.orderNo = rowData.orderNo;
            vm.paymentChangeVisible = true;
        },
        //支付方式修改
        updatePayType: function () {
            if (vm.erpOrder.payment == vm.erpOrderPayNow) {
                alert("选择的支付方式与当前支付方式一致，无需更改！")
                return;
            } else {
                var order = {'orderNo': '', payment: ''};
                order.orderNo = vm.erpOrder.orderNo;
                order.payment = vm.erpOrder.payment;
                //发送请求修改支付方式
                $.ajax({
                    type: "POST",
                    url: baseURL + "order/erporder/updatePayType",
                    contentType: "application/json",
                    data: JSON.stringify(order),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                vm.paymentChangeVisible = false;
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        //查看订单日志
        erpOrderLogDetail: function (orderNo) {
            $.get(baseURL + "order/erporder/erpOrderLog/" + orderNo, function (r) {
                if (r.code == 0) {
                    vm.erpOrderLogData = r.erpOrderLogData;
                    vm.erpOrderLogVisible = true;
                } else {
                    alert(r.msg);
                }
            })
        },


        //订单撤回
        orderRecall: function (orderNo) {
            var rowData = $("#jqGrid").jqGrid('getRowData', orderNo);
            //判断当前订单是不是生产中以及生产完成订单
            this.$confirm('是否确认订单撤回?', '订单撤回提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $.get(baseURL + "order/erporder/orderRecall/" + orderNo, function (r) {
                    if (r.code == 0) {
                        alert("操作成功");
                        vm.reload();
                    } else {
                        alert(r.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        // 订单出库（门店挂账订单、紫云网分配订单）,修改订单发货信息，跳转到erpOrderLogistic页面
        openHangingOrderOut:function(orderNo){
		    //先查询当前订单是否符合操作要求
            $.get(baseURL + "order/erporder/getHangingOrderOutMsg/"+orderNo, function(r) {
                if(r.flag){
                    window.erpOrderLogisticVm.loadData({
                        'orderNo': orderNo,
                        'title': '订单出库'
                    });
                } else {
                    alert("请选择挂账订单或者紫云网订单!");
                }
            })
        },
        // 添加物流，只录入物流信息，无需修改顶顶那发货信息，跳转到erpOrderLogistic页面
        openOrderLogi: function (orderNo) {
            window.erpOrderLogisticVm.loadData({
                'orderNo': orderNo,
                'title': '添加物流'
            });
            // window.location.href = '/modules/order/erpOrderLogistic.html?orderNo=' + orderNo;
        },
        //打开收银结算dialog 快捷键 F2
        openReceviceMoneyQuick: function () {
            // 默认选中扫码行
            $("#jqGrid").jqGrid('setSelection', vm.q.orderNo);
            this.openReceviceMoney();

        },
        //打开收银结算dialog
        openReceviceMoney: function () {
            var orderNo = getSelectedRow();
            if (orderNo == null) {
                return;
            }
            //清空之前数据
            vm.recMoney = {
                discountRate: null, orderNo: '', memberName: '', totalMount: 0, memberId: 0, money: '',
                discount: null, payed: 0, advance: 0, payName: '', memo: '', serialCode: '', paymentId: ''
            };
            //先根据订单号查询出订单相关信息
            //先查询当前订单是否符合操作要求
            $.get(baseURL + "order/erporder/getReceviceMoneyData/" + orderNo, function (r) {
                if (r.code == 0) {
                    vm.e.payTypeEnum = r.payTypeEnum;
                    vm.recMoney = r.recMoney;
                    vm.receviceMoneyVisible = true;
                    setTimeout(function(){
                            vm.payTypeChange("扫码支付");
                         }
                    );
                } else {
                    alert(r.msg);
                }
            })
        },
        //打开批量收银
        openBatchReceviceMoney:function(){
            //先获取所有勾选订单号
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            //清空之前数据
            vm.batchRecMoney = {
                memberName: '', total: 0,money:0, advance: 0, payedAmount: 0, payName: '', serialCode: '', paymentId: '',memberId:'',orderNos:''};
            //先查询当前订单是否符合操作要求
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/getBatchReceviceMoneyData",
                contentType: "application/json",
                data: JSON.stringify(ids),
                success: function (r) {
                if (r.code == 0) {
                    vm.e.payTypeEnum = r.payTypeEnum;
                    vm.batchRecMoney = r.batchRecMoney;
                    vm.batchRecMoneyVisible=true;
                    setTimeout(function(){
                            vm.batchPayTypeChange("扫码支付");
                        }
                    );
                } else {
                    alert(r.msg);
                }
            }});
        },

        cancelReceviceMoney: function () {
            this.$confirm('是否确认取消收银?', '取消收银提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                vm.receviceMoneyVisible = false;
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        //成本录入完成
        confirmCost: function (orderNo) {
            this.$confirm('是否确认成本录入完成?', '成本录入完成提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $.get(baseURL + "order/erporder/confirmCost/" + orderNo, function (r) {
                    if (r.code == 0) {
                        alert("操作成功");
                        vm.reload();
                    } else {
                        alert(r.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },

        payTypeChange: function (value) {
            if (value === '扫码支付') {
                this.$refs.payTypeRef.blur();
                var self = this;
                setTimeout(function () {
                    self.$refs.serialCodeRef.focus();
                }, 500);
            }
            Vue.set(vm.batchRecMoney,"payName",value);
        },

        batchPayTypeChange: function (value) {
            if (value === '扫码支付') {
                this.$refs.batchPayTypeRef.blur();
                var self = this;
                setTimeout(function () {
                    self.$refs.batchSerialCodeRef.focus();
                }, 500);
            }
            Vue.set(vm.batchRecMoney,"payName",value);
        },


        serialCodeChange: function (value) {
            if (isBlank(value)) {
                return;
            }
            // 1.请求后台写入支付ready 流水
            // 开启加载框
            this.loading = this.$loading({
                lock: true,
                text: '扫码支付中,请勿刷新页面!',
                spinner: 'el-icon-loading',
            });
            var self = this;
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/sweepCodeBegin",
                contentType: "application/json",
                data: JSON.stringify(vm.recMoney),
                success: function (r) {
                    if (r.code == 0) {
                        // 2.调用银联ocx 支付
                        vm.recMoney.paymentId = r.paymentId;
                        DUmsocx1 = r.DUmsocx1;
                        ToggleConnectionClicked();
                    } else {
                        // 关闭加载框
                        self.loading.close();
                        alert(r.msg);
                    }
                }
            });
        },

        //扫码支付回调
        sweepCodeCallBack: function (data) {
            if(vm.batchRecMoneyVisible==true&&vm.receviceMoneyVisible==false){
                vm.batchSweepCodeCallBack(data);
                return;
            }else{
                vm.recMoney.sweepCodeData = data;
                var self = this;
                $.ajax({
                    type: "POST",
                    url: baseURL + "order/erporder/sweepCodeCallBack",
                    contentType: "application/json",
                    data: JSON.stringify(vm.recMoney),
                    success: function (r) {
                        // 关闭加载框
                        self.loading.close();
                        if (r.code == 0) {
                            // 此处关闭弹窗
                            vm.receviceMoneyVisible = false;
                            self.$message({
                                message: '付款成功!',
                                type: 'success'
                            });
                            vm.reload();
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
        },

        //批量扫码支付
        batchSerialCodeChange:function(value){
            if (isBlank(value)) {
                return;
            }
            // 1.请求后台写入支付ready 流水
            // 开启加载框
            this.loading = this.$loading({
                lock: true,
                text: '扫码支付中,请勿刷新页面!',
                spinner: 'el-icon-loading',
            });
            var self = this;
            $.ajax({
                    type: "POST",
                    url: baseURL + "order/erporder/batchSweepCodeBegin",
                    contentType: "application/json",
                    data: JSON.stringify(vm.batchRecMoney),
                    success: function (r) {
                        if (r.code == 0) {
                            // 2.调用银联ocx 支付
                            vm.batchRecMoney.paymentId = r.paymentId;
                            DUmsocx1 = r.DUmsocx1;
                            ToggleConnectionClicked();
                        } else {
                            // 关闭加载框
                            self.loading.close();
                            alert(r.msg);
                        }
                    }
            });
        },
        //批量扫码支付回调
        batchSweepCodeCallBack: function (data) {
            vm.batchRecMoney.sweepCodeData = data;
            var self = this;
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/batchSweepCodeCallBack",
                contentType: "application/json",
                data: JSON.stringify(vm.batchRecMoney),
                success: function (r) {
                    // 关闭加载框
                    self.loading.close();
                    if (r.code == 0) {
                        // 此处关闭弹窗
                        vm.batchRecMoneyVisible = false;
                        self.$message({
                            message: '付款成功!',
                            type: 'success'
                        });
                        vm.reload();
                    } else {
                        alert(r.msg);
                    }
                }
            });

        },

        //向后台发起收银请求
        saveReceiveMoney: function () {
            //效验收银参数
            if (!vm.validateReceiveMoney()) {
                return;
            }
            if (vm.recMoney.payName === '扫码支付') {
                this.$message.error('扫码支付，请进行扫码!');
                return;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/saveReceviceMoney",
                contentType: "application/json",
                data: JSON.stringify(vm.recMoney),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            vm.receviceMoneyVisible = false;
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },

        //向后台发起收银请求
        saveBatchReceiveMoney: function () {
            if (vm.batchRecMoney.payName === '扫码支付') {
                this.$message.error('扫码支付，请进行扫码!');
                return;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/saveBatchReceviceMoney",
                contentType: "application/json",
                data: JSON.stringify(vm.batchRecMoney),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            vm.batchRecMoneyVisible = false;
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },


        //初始化生产单
        createPrintPage() {
            LODOP = getLodop();
            LODOP.PRINT_INIT("Lodop初始化");
            LODOP.SET_PRINT_PAGESIZE(1, 2100, 1350, ""); //第一个参数为1表示纵向
            var curWwwPath = window.document.location.href;
            //获取主机地址之后的目录，
            var pathName = window.document.location.pathname;
            var pos = curWwwPath.indexOf(pathName);
            //获取主机地址，
            var localhostPaht = curWwwPath.substring(0, pos);
            $("#printProduct").append(' <link rel="stylesheet" href="' + localhostPaht + '/statics/css/product.css">');
            var printHtml = document.getElementById("printProduct").innerHTML;
            LODOP.ADD_PRINT_HTM(0, "3%", "95%", "100%", printHtml);
        },
        // 弹出送货单
        createSendPrintPage: function () {
            LODOP = getLodop();
            LODOP.PRINT_INIT("Lodop初始化");
            LODOP.SET_PRINT_PAGESIZE(3, 0, 0, "A4"); //第一个参数为1表示纵向
            LODOP.ADD_PRINT_HTM(0, "1%", "99%", 500, document.getElementById("printbox").innerHTML);
            /*增加超文本项*/
        },
        //打印生产单
        printProdution(orderNo, productionStatus) {
            $.get(baseURL + "order/erporder/info/" + orderNo, function (r) {
                vm.erpOrder = r.erpOrder;
                vm.orderItemDetailData = r.orderItemDetailData;
                //处理数据
                if (vm.orderItemDetailData.length > 0) {
                    for (var i = 0; i < vm.orderItemDetailData.length; i++) {
                        var item = vm.orderItemDetailData[i];
                        var addon = item.addon;
                        if (addon) {
                            //判断是否为json
                            try {
                                var addonArr = JSON.parse(addon);
                                //循环取出 参数
                                var addonStr = '';
                                for (var j = 0; j < addonArr.length; j++) {
                                    var str = '';
                                    var addon = addonArr[j];
                                    var craftParam = addon.craftParam;
                                    var partsName = addon.partsName;
                                    if (partsName) {
                                        str += partsName + ":";
                                    }
                                    if (!$.isEmptyObject(craftParam)) {
                                        for (key in craftParam) {
                                            str += craftParam[key] + ",";
                                        }
                                        //str+=JSON.stringify(craftParam).replace('}','').replace('{','').replace(/\"/g,'');
                                    }
                                    var basicParam = addon.basicParam;
                                    if (!$.isEmptyObject(basicParam)) {
                                        for (key in basicParam) {
                                            if (key != '是否自来纸') {
                                                str += basicParam[key] + ",";
                                            }
                                        }
                                        //str+=JSON.stringify(basicParam).replace('}','').replace('{','').replace(/\"/g,'');
                                    }

                                    addonStr += str;
                                }
                                if (addonStr) {
                                    vm.orderItemDetailData[i].addon = addonStr;
                                }

                            } catch (err) {
                                //不做处理
                            }
                        }
                        // cutModel 转换
                        if (!$.isEmptyObject(item.cutModel)) {
                            item.cutModelObj = JSON.parse(item.cutModel);
                        }
                        //处理工艺
                    }
                }
                // 配置条码显示
                JsBarcode("#code128", vm.erpOrder.orderNo,
                    {height: 50, displayValue: false, margin: 1, marginLeft: 50, marginTop: 10});

                LODOP = getLodop();
                LODOP.PRINT_INIT("");
                layer.open({
                    type: 1,
                    skin: 'layer-ext-moon',
                    title: "打印生产单",
                    area: ['750px', '550px'],
                    shadeClose: false,
                    content: jQuery("#printProduct"),
                    btn: ['打印', '取消'],
                    btn1: function (index) {
                        vm.createPrintPage();
                        LODOP.PRINT();
                        //LODOP.PREVIEW();
                        //修改订单状态,新开单->生产中
                        if (productionStatus == 7) {
                            $.get(baseURL + "order/erporder/updateStatus/" + orderNo + "/3", function (r) {
                                if (r.code === 0) {
                                    vm.reload()
                                } else {
                                    alert(r.msg);
                                }
                            });
                        }
                        layer.closeAll();
                    }
                });
            });
        },
        //初始化结算单
        createBalancePage() {
            LODOP = getLodop();
            LODOP.PRINT_INIT("Lodop初始化");
            LODOP.SET_PRINT_PAGESIZE(1, 2100, 1350, ""); //第一个参数为1表示纵向
            LODOP.ADD_PRINT_HTM(0, "3%", "95%", "100%", document.getElementById("printBalance").innerHTML);
        },
        //打印结算单
        printBalancePage(orderNo) {
            $.get(baseURL + "order/erporder/printBalance/" + orderNo, function (r) {
                //先清空前一个二维码
                $('#qrcode').html("")
                vm.count=0
                vm.erpOrder = r.erpOrder;
                jQuery('#qrcode').qrcode({
                    width:120,
                    height:120,
                    text: 'http://test.11ziyun.com/wap/paycenter/erpwxpay/'+ vm.erpOrder.orderNo,
                });
                var img = document.getElementById("image"); /// get image element
                var canvas  = document.getElementsByTagName("canvas")[0];
                img.src = canvas.toDataURL();
                vm.orderItemDetailData = r.orderItemDetailData;
                //处理数据
                if (vm.orderItemDetailData.length > 0) {
                    for (var i = 0; i < vm.orderItemDetailData.length; i++) {
                        var item = vm.orderItemDetailData[i];
                        var addon = item.addon;
                        if (addon) {
                            //判断是否为json
                            try {
                                var addonArr = JSON.parse(addon);
                                //循环取出 参数
                                var addonStr = '';
                                for (var j = 0; j < addonArr.length; j++) {
                                    var str = '';
                                    var addon = addonArr[j];
                                    var craftParam = addon.craftParam;
                                    var partsName = addon.partsName;
                                    if (partsName) {
                                        str += partsName + ":";
                                    }
                                    if (!$.isEmptyObject(craftParam)) {
                                        for (key in craftParam) {
                                            str += craftParam[key] + ",";
                                        }
                                    }
                                    var basicParam = addon.basicParam;
                                    if (!$.isEmptyObject(basicParam)) {
                                        for (key in basicParam) {
                                            if (key != '是否自来纸') {
                                                str += basicParam[key] + ",";
                                            }
                                        }
                                    }

                                    addonStr += str;
                                }
                                if (addonStr) {
                                    vm.orderItemDetailData[i].addon = addonStr;
                                }

                            } catch (err) {
                                //不做处理
                            }
                        }
                        // cutModel 转换
                        if (!$.isEmptyObject(item.cutModel)) {
                            item.cutModelObj = JSON.parse(item.cutModel);
                        }
                        //处理工艺
                    }
                }

                vm.courrentUser = r.curentUser
                vm.sellerInfoEntity = r.sellerInfoEntity
                LODOP = getLodop();
                LODOP.PRINT_INIT("");
                layer.open({
                    type: 1,
                    skin: 'layui-layer-molv',
                    title: "打印结算单",
                    area: ['850px', '550px'],
                    shadeClose: false,
                    content: jQuery("#printBalance"),
                    btn: ['打印', '取消'],
                    btn1: function (index) {
                        vm.createBalancePage();
                        LODOP.PRINT();
                        // LODOP.PREVIEW();
                        layer.closeAll();
                    }
                });
            });
        },
        //打印送货单
        printSendGoods: function (orderNo) {
            $.get(baseURL + "order/orderinfo/mall/printGoods?orderId=" + orderNo, function (r) {
                if (r.code == 0) {
                    vm.print.orderInfo = r.orderInfo;
                    vm.print.orderItemList = r.orderItemList;
                    LODOP = getLodop();
                    LODOP.PRINT_INIT("");
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-molv',
                        title: "打印送货单",
                        area: ['800px', '550px'],
                        shadeClose: false,
                        content: jQuery("#printGoods"),
                        btn: ['打印', '取消'],
                        btn1: function (index) {
                            vm.createSendPrintPage();
                            LODOP.PRINT();
                            // LODOP.PREVIEW();
                            layer.closeAll();
                        }
                    });
                } else {
                    alert(r.msg);
                }
            });
        },

        //初始化批量结算单
        createBatchPage() {
            LODOP = getLodop();
            LODOP.PRINT_INIT("Lodop初始化");
            LODOP.SET_PRINT_PAGESIZE(1, 2100, 1350, ""); //第一个参数为1表示纵向
            LODOP.ADD_PRINT_HTM(0, "3%", "95%", "100%", document.getElementById("batchBalance").innerHTML);
        },
        //打印批量结算单
        printBatchPage() {
            //先获取所有勾选订单号
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/generateBatchProduct",
                contentType: "application/json",
                data: JSON.stringify(ids),
                success: function (r) {
                    if (r.code == 0) {
                        vm.batchProduct=r.data;
                        vm.courrentUser = r.curentUser
                        vm.sellerInfoEntity = r.sellerInfoEntity
                        //先清空前一个二维码
                        $('#batchCode').html("");
                        $('#batchImage').src="";
                        jQuery('#batchCode').qrcode({
                            width:120,
                            height:120,
                            text: 'http://test.11ziyun.com/wap/paycenter/erpwxpay/'+vm.batchProduct.orderNos,
                        });
                        var img = document.getElementById("batchImage"); /// get image element
                        var canvas  = document.getElementById("batchCode").getElementsByTagName("canvas")[0];
                        img.src = canvas.toDataURL();
                        LODOP = getLodop();
                        LODOP.PRINT_INIT("");
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-molv',
                            title: "打印结算单",
                            area: ['850px', '550px'],
                            shadeClose: false,
                            content: jQuery("#batchBalance"),
                            btn: ['打印', '取消'],
                            btn1: function (index) {
                                vm.createBatchPage();
                                LODOP.PRINT();
                                layer.closeAll();
                            }
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },

        //效验收银参数
        validateReceiveMoney: function () {
            if (vm.recMoney.payName == undefined) {
                alert("请选择支付方式再操作");
                return false;
            }
            if (vm.recMoney.money == undefined) {
                alert("请输入支付金额再操作");
                return false;
            }

            var payableAmount = vm.recMoney.payableAmount;
            var money = vm.recMoney.money;
            var payableMoneyFloor = Math.floor(Number(payableAmount));// 向下取整金额
            if (Number(money) < Number(payableMoneyFloor)) {
                alert("收款金额只支持抹零");
                vm.recMoney.money = payableAmount;
                return false;
            }

            return true;
        },
        //处理选择客户的挂账客户显示
        formatterAccountCustomer: function (row, column) {
            return row.hangsAccountCustomer ? "挂账客户" : "非挂账客户"
        },

        //算价相关方法
        /* 算价 */
        caculateQuote: function () {
            vm.caculateQuoteData.categoryId = vm.q.printZiyunCategoryId;
            vm.caculateQuoteData.memberId = vm.erpOrder.memberId;
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/caculateQuote",
                contentType: "application/json",
                data: JSON.stringify(vm.caculateQuoteData),
                success: function (r) {
                    if (r.code == 0) {
                        vm.factoryQuoteInfoList = r.factoryQuoteInfoList;
                        vm.quotePriceDialogVisible = true;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        fastCaculateQuote: function () {
            vm.caculateQuoteData.categoryId = vm.q.fastZiyunCategoryId;
            vm.caculateQuoteData.memberId = vm.erpOrder.memberId;
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/fastCaculateQuote",
                contentType: "application/json",
                data: JSON.stringify(vm.caculateQuoteData),
                success: function (r) {
                    if (r.code == 0) {
                        vm.fastFactoryQuoteInfoList = r.fastFactoryQuoteInfoList;
                        //cutModel 转换为对象
                        if (vm.fastFactoryQuoteInfoList.length == 1) { //快印就一个价格
                            var cutModelTemp = vm.fastFactoryQuoteInfoList[0].cutModel;
                            if (cutModelTemp) {
                                vm.fastFactoryQuoteInfoList[0].cutModelObj = JSON.parse(cutModelTemp);
                            }

                        }
                        vm.fastQuotePriceDialogVisible = true;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //选择商务印刷商品
        selectPrintGoods: function (index) {
            vm.printGoods = {};
            var row = vm.factoryQuoteInfoList[vm.printIndex];
            vm.printGoods.productId = row.productId;
            vm.printGoods.productName = row.productName;
            vm.printGoods.quantity = row.quantity;
            vm.printGoods.price = row.unitPrice;
            vm.printGoods.total = row.totalPrice;
            vm.printGoods.goodsType = "print";
            vm.printGoods.calculationPriceProcess = row.priceProcess;
            vm.printGoods.craft = row.addon;
            vm.printGoods.productInfoParamList = row.productInfoParamList;
            vm.printGoods.attributeOption = row.attributeOption;
            vm.printGoods.quoteSelfDefineParam = row.quoteSelfDefineParam;
            vm.printGoods.cutModel = row.cutModel;
        },
        addPrintGoods: function () {
            //如果没有更改过直接取默认值
            if (vm.printIndex == 2) {
                var row = vm.factoryQuoteInfoList[vm.printIndex];
                vm.printGoods.productId = row.productId;
                vm.printGoods.productName = row.productName;
                vm.printGoods.quantity = row.quantity;
                vm.printGoods.price = row.unitPrice;
                vm.printGoods.total = row.totalPrice;
                vm.printGoods.goodsId = row.goodsId;
                vm.printGoods.goodsType = "print";
                vm.printGoods.craft = row.addon;
                vm.printGoods.calculationPriceProcess = row.priceProcess;
                vm.printGoods.productInfoParamList = row.productInfoParamList;
                vm.printGoods.attributeOption = row.attributeOption;
                vm.printGoods.quoteSelfDefineParam = row.quoteSelfDefineParam;
                vm.printGoods.cutModel = row.cutModel;
            }
            //如果输入了金额，对总价重新计算
            if (vm.printMoney != 0) {
                vm.printGoods.itemRemark = "商品原价为:" + vm.printGoods.total + "修改后的价格为:" + vm.printMoney;
                vm.printGoods.total = vm.printMoney;
                vm.printGoods.price = (vm.printGoods.total / vm.printGoods.quantity).toFixed(4);
            }
            var printGoods = JSON.parse(JSON.stringify(vm.printGoods));
            vm.detailData.push(printGoods);
            vm.quotePriceDialogVisible = false;
            //清空选择和输入的数据
            vm.printMoney = 0;
            vm.printIndex = 2;
            vm.printGoods.itemRemark = "";
        },
        //添加快印商品
        addFastGoods: function () {
            var row = vm.fastFactoryQuoteInfoList[0];
            vm.fastGoods.productId = row.productId;
            vm.fastGoods.productName = row.productName;
            vm.fastGoods.quantity = row.quantity;
            vm.fastGoods.price = row.unitPrice;
            vm.fastGoods.total = row.totalPrice;
            vm.fastGoods.goodsType = "fast";
            vm.fastGoods.craft = row.addon;
            vm.fastGoods.goodsId = row.goodsId;
            vm.fastGoods.priceProcess = row.priceProcess;
            vm.fastGoods.productInfoParamList = row.productInfoParamList;
            vm.fastGoods.attributeOption = row.attributeOption;
            vm.fastGoods.quoteSelfDefineParam = row.quoteSelfDefineParam;
            vm.fastGoods.cutModel = row.cutModel;
            vm.fastGoods.cutModelObj = row.cutModelObj;
            //如果输入了金额，对总价重新计算
            if (vm.fastMoney != 0) {
                vm.fastGoods.itemRemark = "商品原价为:" + vm.fastGoods.total + "修改后的价格为:" + vm.fastMoney;
                vm.fastGoods.total = vm.fastMoney;
                vm.fastGoods.price = (vm.fastGoods.total / vm.fastGoods.quantity).toFixed(4);
            }
            var fastGoods = JSON.parse(JSON.stringify(vm.fastGoods));
            vm.detailData.push(fastGoods);
            vm.fastQuotePriceDialogVisible = false;
            //清空选择和输入的数据
            vm.fastMoney = 0;
            vm.fastGoods.itemRemark = "";
        },


        //删除订单详情中的商品
        deleteGoods: function (index) {
            vm.detailData.splice(index, 1);
        },

        // 如果没有额外属性不显示按钮
        getRowClass: function (row, index) {
            if (row.row.productInfoParamList == null
                || row.row.productInfoParamList == undefined) {  //判断当前行是否有子数据
                return 'row-expand-cover'
            }
        },
        //开始修改
        startUpdatePrice: function () {
            //保存
            if (vm.updateItemPriceFlag) {
                vm.erpOrderItemDto.erpOrderItemList = vm.orderItemDetailData;
                $.ajax({
                    type: "POST",
                    url: baseURL + "order/erporder/startUpdatePrice",
                    contentType: "application/json",
                    data: JSON.stringify(vm.erpOrderItemDto),
                    success: function (r) {
                        if (r.code == 0) {
                            vm.getInfo(vm.erpOrder.orderNo);
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
            vm.updateItemPriceFlag = !vm.updateItemPriceFlag;
        },
        //修改优惠以及项目名称
        updatePmtGoods: function () {
            if (vm.erpOrder.pmtGoods < 0) {
                alert("优惠金额不能小于0");
                vm.erpOrder.pmtGoods = 0;
            }
            //保存
            if (vm.updateOrderPmtGoodsFlag) {
                var order = {orderNo: '', pmtGoods: '',projectName:''};
                order.orderNo = vm.erpOrder.orderNo;
                order.pmtGoods = vm.erpOrder.pmtGoods;
                order.projectName=vm.erpOrder.projectName;
                $.ajax({
                    type: "POST",
                    url: baseURL + "order/erporder/updatePmtGoods",
                    contentType: "application/json",
                    data: JSON.stringify(order),
                    success: function (r) {
                        if (r.code == 0) {
                            alert("操作成功!");
                            vm.getInfo(vm.erpOrder.orderNo);
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
            vm.updateOrderPmtGoodsFlag = !vm.updateOrderPmtGoodsFlag;
        },
        changeItemNums: function (row) {
            for (var i = 0; i < vm.recordItemData.length; i++) {
                var item = vm.recordItemData[i];
                if (row.eoItemId == item.eoItemId) {
                    if (isNaN(Number(row.nums))) {
                        alert("请确保输入的为数字");
                        row.nums = item.nums;
                        return;
                    } else {
                        //如果不是广告物料，则直接计算
                        if (row.addcartBuyType != 'material') {
                            row.amount = row.price * row.nums;
                        }
                        if (row.addcartBuyType == 'material') {
                            //先获取尺寸
                            if (row.addon.indexOf("周长") > -1 || row.addon.indexOf("长度") > -1) {
                                var length = Number(row.addon.substring(row.addon.lastIndexOf(":") + 1));
                                row.amount = row.price * row.amount * row.nums * length;
                            }
                            if (row.addon.indexOf("面积") > -1) {
                                var str = row.addon.substring(row.addon.lastIndexOf(":") + 1);
                                var split = str.split("*");
                                var length = Number(split[0]);
                                var width = Number(split[1]);
                                row.amount = row.price * row.nums * length * width;
                            }
                        }
                    }
                }
            }
        },
        //监听修改总价
        changeItemPrice: function (row) {
            for (var i = 0; i < vm.recordItemData.length; i++) {
                var item = vm.recordItemData[i];
                if (row.eoItemId == item.eoItemId) {
                    if (row.amount < item.amount) {
                        row.amount = item.amount;
                        alert("修改金额不能小于原始金额");
                    } else {
                        //如果不是广告物料，则直接计算
                        if (row.addcartBuyType != 'material') {
                            if(row.copy==null||row.copy==undefined){
                                row.copy=1;
                            }
                            row.price = (row.amount / row.nums/row.copy).toFixed(4);
                            row.sharePrice = row.price;
                        }
                        if (row.addcartBuyType == 'material') {
                            //先获取尺寸
                            if (row.addon.indexOf("周长") > -1 || row.addon.indexOf("长度") > -1) {
                                var length = Number(row.addon.substring(row.addon.lastIndexOf(":") + 1));
                                row.price = (row.amount / row.nums / length).toFixed(4);
                                row.sharePrice = row.price;
                            }
                            if (row.addon.indexOf("面积") > -1) {
                                var str = row.addon.substring(row.addon.lastIndexOf(":") + 1);
                                var split = str.split("*");
                                var length = Number(split[0]);
                                var width = Number(split[1]);
                                row.price = (row.amount / row.nums / length / width).toFixed(4);
                                row.sharePrice = row.price;
                            }
                        }
                    }
                }
            }
        },
        //批量录入成本
        batchEnter: function () {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            this.$confirm('是否确认批量录入, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm') {
                        var postData = ids.join(',');
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/erporder/batchEnter?ids=" + postData,
                            contentType: "application/json",
                            data: null,
                            success: function (r) {
                                if (r.code === 0) {
                                    alert("操作成功!");
                                    vm.reload();
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        //格式化发票类型
        formatTaxType(row, column, cellValue) {
            for (var i = 0; i < vm.e.taxTypeEnum.length; i++) {
                if (cellValue == vm.e.taxTypeEnum[i].value) {
                    return vm.e.taxTypeEnum[i].describe;
                }
            }
        },
        //新算价方法
        //算价添加商品点击事件
        zyAddGoods: function (data) {
            this.detailData.push.apply(this.detailData, data);
        },
    }
});
/** 数字金额大写转换(可以处理整数,小数,负数) */
function smalltoBIG(n) {
    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);

    var s = '';

    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}